const dayjs = require('dayjs');
const { observable, action, computed } = require('mobx-miniprogram');
const dateHelper = require('../../../store/helpers/date_helper');

// 定义项目缓存Key
const PROJECT_LIST_CACHE_KEY = 'PROJECT_LIST_CACHE_KEY';
const PROJECT_DETAIL_CACHE_KEY = 'PROJECT_DETAIL_CACHE_KEY_';
const CACHE_EXPIRE_TIME = 30 * 60 * 1000; // 30分钟

// 项目模块Store
export const projectStore = observable({
  // 项目列表
  projectList: [],
  
  // 当前项目详情
  currentProject: null,
  
  // 列表状态
  listStatus: {
    loading: false,
    error: null,
    lastUpdateTime: null,
    hasMore: true,
    page: 1,
    size: 20
  },
  
  // 详情状态
  detailStatus: {
    loading: false,
    error: null,
    projectId: ''
  },
  
  // 搜索条件
  searchCondition: {
    search: '',
    sortType: 'time', // time, hot
    cateId: -1,
    status: -1, 
    activeStatus: -1
  },
  
  // 统计数据
  statistics: {
    total: 0,
    byStatus: {},
    byCategory: {}
  },
  
  // 获取项目类别列表
  get cateList() {
    return [
      { label: '全部', value: -1 },
      { label: '产品研发', value: 0 },
      { label: '技术研究', value: 1 },
      { label: '平台建设', value: 2 },
      { label: '工具开发', value: 3 },
      { label: '其他', value: 4 }
    ];
  },
  
  // 获取项目状态列表
  get statusList() {
    return [
      { label: '全部', value: -1 },
      { label: '进行中', value: 0 },
      { label: '已完成', value: 1 },
      { label: '已取消', value: 2 }
    ];
  },
  
  // 获取项目激活状态列表
  get activeStatusList() {
    return [
      { label: '全部', value: -1 },
      { label: '未激活', value: 0 },
      { label: '已激活', value: 1 }
    ];
  },
  
  // 计算属性：获取最近更新的项目
  get recentProjects() {
    // 使用Day.js处理日期排序
    return [...this.projectList]
      .sort((a, b) => dateHelper.dayjs(b.updateTime).valueOf() - dateHelper.dayjs(a.updateTime).valueOf())
      .slice(0, 5);
  },
  
  // 计算属性：按类别分组的项目
  get projectsByCategory() {
    const result = {};
    
    // 初始化类别组
    this.cateList.forEach(cate => {
      if (cate.value !== -1) {
        result[cate.value] = [];
      }
    });
    
    // 分类项目
    this.projectList.forEach(project => {
      if (result[project.projectType] !== undefined) {
        result[project.projectType].push(project);
      }
    });
    
    return result;
  },
  
  // 计算属性：即将到期的项目
  get upcomingDeadlineProjects() {
    const now = dateHelper.now();
    const oneWeekLater = dateHelper.add(now, 7, 'day');
    
    return this.projectList
      .filter(project => {
        if (project.level1 !== 3) return false; // 只关注活动中的项目 (level1=3表示活动)
        
        // 判断截止日期是否在一周内
        return dateHelper.isBetween(
          project.deadline,
          now,
          oneWeekLater
        );
      })
      .sort((a, b) => dateHelper.dayjs(a.deadline).valueOf() - dateHelper.dayjs(b.deadline).valueOf());
  },
  
  // 计算属性：获取项目状态文本
  getProjectStatusText(project) {
    if (!project) return '';
    
    // 使用level状态系统获取状态文本
    switch (project.level1) {
      case 1:
        return '项目审核';
      case 2:
        return '休眠';
      case 3:
        return '活动';
      case 99:
        return '已完成';
      default:
        return '未知状态';
    }
  },
  
  // 计算属性：获取格式化的项目截止日期
  getProjectDeadlineFormatted(project) {
    if (!project || !project.deadline) return '';
    return dateHelper.formatDate(project.deadline);
  },
  
  // 计算属性：获取友好的项目创建时间
  getProjectCreateTimeFriendly(project) {
    if (!project || !project.createTime) return '';
    return dateHelper.formatFriendly(project.createTime);
  },
  
  // 计算属性：获取项目截止状态 (已过期、即将到期、正常)
  getProjectDeadlineStatus(project) {
    if (!project || !project.deadline) return 'normal';
    
    const now = dateHelper.now();
    const deadline = project.deadline;
    
    if (deadline < now) return 'expired';
    
    const daysLeft = dateHelper.diff(deadline, now, 'day');
    if (daysLeft <= 7) return 'warning';
    
    return 'normal';
  },
  
  // Action: 初始化列表
  initList: action(function() {
    // 使用内置缓存方法
    try {
      const cache = wx.getStorageSync(PROJECT_LIST_CACHE_KEY);
      if (cache) {
        this.projectList = cache.list || [];
        this.statistics = cache.statistics || {
          total: 0,
          byStatus: {},
          byCategory: {}
        };
        this.listStatus.lastUpdateTime = cache.time;
        
        // 检查缓存是否需要刷新
        const now = dateHelper.now();
        if (now - cache.time > CACHE_EXPIRE_TIME) { // 缓存30分钟
          this.refreshList();
        }
      } else {
        this.refreshList();
      }
    } catch (e) {
      console.error('Failed to init project list from cache', e);
      this.refreshList();
    }
  }),
  
  // Action: 刷新列表
  refreshList: action(async function() {
    try {
      this.listStatus.loading = true;
      this.listStatus.error = null;
      this.listStatus.page = 1;
      this.listStatus.hasMore = true;
      
      await this.loadList(true);
    } catch (e) {
      console.error('Failed to refresh project list', e);
      this.listStatus.error = e.message || '加载失败';
    } finally {
      this.listStatus.loading = false;
    }
  }),
  
  // Action: 加载列表
  loadList: action(async function(refresh = false) {
    try {
      if (this.listStatus.loading) return;
      if (!this.listStatus.hasMore && !refresh) return;
      
      this.listStatus.loading = true;
      this.listStatus.error = null;
      
      // 模拟从服务器加载数据
      const mockData = {
        data: [
          {
            id: '1',
            projectTitle: '示例项目1',
            projectCode: 'PRJ001',
            projectManagerName: '张三',
            createTime: dateHelper.now(),
            deadline: dateHelper.add(dayjs(), 30, 'day').valueOf(),
            level1: 3, // 活动状态
            projectType: 0,
            progress: 30
          },
          {
            id: '2',
            projectTitle: '示例项目2',
            projectCode: 'PRJ002',
            projectManagerName: '李四',
            createTime: dateHelper.subtract(dayjs(), 10, 'day').valueOf(),
            deadline: dateHelper.add(dayjs(), 60, 'day').valueOf(),
            level1: 99, // 已完成状态
            projectType: 1,
            progress: 100
          }
        ],
        statistics: {
          total: 2,
          byStatus: {
            "3": 1,  // 活动
            "99": 1  // 已完成
          },
          byCategory: {
            "0": 1,
            "1": 1
          }
        }
      };
      
      // 正常情况下应该请求云函数获取数据
      // 省略调用云函数的代码...
      
      // 处理分页逻辑
      const list = mockData.data;
      const newList = refresh ? list : [...this.projectList, ...list];
      
      this.projectList = newList;
      this.statistics = mockData.statistics;
      this.listStatus.lastUpdateTime = dateHelper.now();
      this.listStatus.hasMore = list.length >= this.listStatus.size;
      this.listStatus.page++;
      
      // 缓存数据
      wx.setStorageSync(PROJECT_LIST_CACHE_KEY, {
        list: newList,
        statistics: mockData.statistics,
        time: this.listStatus.lastUpdateTime
      });
    } catch (e) {
      console.error('Failed to load project list', e);
      this.listStatus.error = e.message || '加载失败';
    } finally {
      this.listStatus.loading = false;
    }
  }),
  
  // Action: 加载更多
  loadMore: action(async function() {
    if (this.listStatus.loading || !this.listStatus.hasMore) return;
    
    await this.loadList();
  }),
  
  // Action: 加载项目详情
  loadProjectDetail: action(async function(projectId) {
    try {
      if (!projectId) throw new Error('项目ID不能为空');
      
      this.detailStatus.loading = true;
      this.detailStatus.error = null;
      this.detailStatus.projectId = projectId;
      
      // 优先从列表中查找
      let project = this.projectList.find(p => p.id === projectId);
      
      // 如果列表中没有，尝试从缓存中获取
      if (!project) {
        const cacheKey = PROJECT_DETAIL_CACHE_KEY + projectId;
        try {
          const cache = wx.getStorageSync(cacheKey);
          if (cache && cache.data && (dateHelper.now() - cache.time < CACHE_EXPIRE_TIME)) {
            project = cache.data;
          }
        } catch (e) {
          console.error('Failed to get project detail from cache', e);
        }
      }
      
      // 如果缓存中也没有，请求服务器获取
      if (!project) {
        // 模拟请求服务器获取项目详情
        // 正常情况下应该请求云函数获取数据
        project = {
          id: projectId,
          projectTitle: '示例项目详情',
          projectCode: 'PRJ-DETAIL',
          projectName: '示例项目',
          projectDesc: '这是一个示例项目的详情描述',
          projectManagerName: '项目经理',
          projectManagerId: 'manager001',
          teamMemberNames: ['张三', '李四', '王五'],
          teamMemberIds: ['user001', 'user002', 'user003'],
          createTime: dateHelper.now(),
          updateTime: dateHelper.now(),
          startDate: dateHelper.subtract(dayjs(), 10, 'day').valueOf(),
          deadline: dateHelper.add(dayjs(), 30, 'day').valueOf(),
          level1: 3,
          level3: 'debug',
          statusDesc: '活动 - 调试',
          projectType: 0,
          progress: 45
        };
        
        // 缓存项目详情
        wx.setStorageSync(PROJECT_DETAIL_CACHE_KEY + projectId, {
          data: project,
          time: dateHelper.now()
        });
      }
      
      this.currentProject = project;
    } catch (e) {
      console.error('Failed to load project detail', e);
      this.detailStatus.error = e.message || '加载项目详情失败';
    } finally {
      this.detailStatus.loading = false;
    }
  }),
  
  // Action: 清除详情
  clearProjectDetail: action(function() {
    this.currentProject = null;
    this.detailStatus.projectId = '';
    this.detailStatus.error = null;
  }),
  
  // Action: 设置搜索条件
  setSearchCondition: action(function(condition) {
    Object.assign(this.searchCondition, condition);
    this.refreshList();
  }),
  
  // Action: 重置搜索条件
  resetSearchCondition: action(function() {
    this.searchCondition = {
      search: '',
      sortType: 'time',
      cateId: -1,
      status: -1,
      activeStatus: -1
    };
    this.refreshList();
  })
}); 